import { Injectable } from '@nestjs/common';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { QueryPostDto } from './dto/query-post.dto';
import {DeletePostDto} from './dto/delete-post.dto';
import { Request, Response } from 'express';
import { User } from '../user/entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Post } from './entities/post.entity';
import { Repository } from 'typeorm';
import { Workbook } from 'exceljs';
import { StatusChangeDto } from 'src/common/baseDto/status-change.dto';

@Injectable()
export class PostService {
  constructor(
    @InjectRepository(Post) private postRepository: Repository<Post>,
  ) {}

  /**
   * 创建岗位
   * @param createPostDto
   * @param req
   * @returns
   */
  create(createPostDto: CreatePostDto, req: Request) {
    let user = req.user as User;
    createPostDto.create_by = user.username;
    return this.postRepository.save(createPostDto);
  }

  /**
   * 获取岗位列表
   * @param query 
   * @returns 
   */
  async findAll(query:QueryPostDto) {
    let queryBuilder = this.postRepository.createQueryBuilder('post');
    if(query.post_code) {
      queryBuilder.andWhere('post.post_code like :post_code',{post_code:`%${query.post_code}%`});
    }
    if(query.post_name) {
      queryBuilder.andWhere('post.post_name like :post_name',{post_name:`%${query.post_name}%`});
    }
    if(query.status) {
      queryBuilder.andWhere('post.status = :status',{status:query.status});
    }

    // 处理分页
    if (!query.pageNum || query.pageNum < 1) {
      query.pageNum = 1;
    }
    if (!query.pageSize || query.pageSize < 1) {
      query.pageSize = 10;
    }
    queryBuilder = queryBuilder
      .groupBy('post.post_id')
      .skip((query.pageNum - 1) * query.pageSize)
      .take(query.pageSize);

    let total = await queryBuilder.getCount();
    let list = await queryBuilder.getMany();
    return {
      pageNum: query.pageNum,
      pageSize: query.pageSize,
      total: total,
      list: list,
    };
  }

  /**
   * 获取岗位详情
   * @param id 
   * @returns 
   */
  findOne(id: number) {
    return this.postRepository.findOne({where:{post_id:id}});
  }

  /**
   * 更新岗位
   * @param id 
   * @param updatePostDto 
   * @param req 
   * @returns 
   */
  update(id: number, updatePostDto: UpdatePostDto,req:Request) {
    let user = req.user as User;
    updatePostDto.post.update_by = user.username;
    return this.postRepository.update(id,updatePostDto.post)
  }

  /**
   * 更新岗位状态
   * @param statusChangeDto
   * @param req
   */
  statusChange(statusChangeDto: StatusChangeDto,req:Request) {
    let user = req.user as User;
    return this.postRepository.update(statusChangeDto.id, {
      status: statusChangeDto.status,
      update_by: user.username,
    });
  }

  /**
   * 删除岗位
   * @param deletePostDto 
   * @returns 
   */
  remove(deletePostDto: DeletePostDto) {
    return this.postRepository.delete(deletePostDto.postIds);
  }

  /**
   * 导出为表格
   * @param res 
   */
  async exportToExcel(res:Response) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet('岗位');

    worksheet.columns = [
      { header: '岗位ID', key: 'post_id', width: 10 },
      { header: '岗位编码', key: 'post_code', width: 10 },
      { header: '岗位名称', key: 'post_name', width: 10 },
      { header: '显示顺序', key: 'post_sort', width: 10 },
      { header: '状态（0正常 1停用）', key: 'status', width: 10 },
      { header: '创建者', key: 'create_by', width: 10 },
      { header: '创建时间', key: 'create_time', width: 10 },
      { header: '更新者', key: 'update_by', width: 10 },
      { header: '更新时间', key: 'update_time', width: 10 },
      { header: '备注', key: 'remark', width: 10 },
    ];

    const data = await this.postRepository.find();
    worksheet.addRows(data);
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    let filename = encodeURIComponent('岗位.xlsx'); // 这里中文需要转码
    res.setHeader(
      'Content-Disposition',
      'attachment; filename=' + filename + '',
    );
    res.setHeader('Cache-Control', 'max-age=0');
    const file = await workbook.xlsx.writeBuffer();
    res.end(file);
  }
}
